package org.pay.settlement.service;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.pay.core.common.constant.MchConstant;
import org.pay.core.common.util.DateUtil;
import org.pay.core.common.util.MyLog;
import org.pay.core.entity.MchAccount;
import org.pay.core.entity.MchInfo;
import org.pay.core.entity.MchSettDailyCollect;

import java.util.List;
import java.util.Map;

/**
 * @author: yangshancheng
 * @date: 17/12/3
 * @description:
 */
@Component
public class MchSettService {

    private static final MyLog _log = MyLog.getLog(MchSettService.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    /**
     * 生成商户结算汇总数据
     */
    public void buildSettDailyCollect(String collDate) {
        int pageIndex = 1;
        int limit =100;
        boolean flag = true;
        // 循环查询所有商户账户
        while (flag) {
            List<MchAccount> mchAccountList = rpcCommonService.rpcMchAccountService.listAll((pageIndex - 1) * limit, limit);
            for(MchAccount mchAccount : mchAccountList) {
                // 平台账户且状态为可用的商户,进行结算处理
                if(MchConstant.MCH_TYPE_PLATFORM == mchAccount.getKind() &&
                        MchConstant.PUB_YES == mchAccount.getState()) {
                    long startTime = System.currentTimeMillis();
                    dailySettCollect(mchAccount, collDate);
                    _log.info("商户:{}结算完成,耗时:{} ms", mchAccount.getMchId(), System.currentTimeMillis() - startTime);
                }
            }
            pageIndex++;
            if(CollectionUtils.isEmpty(mchAccountList) || mchAccountList.size() < limit) {
                flag = false;
            }
        }

    }

    public void dailySettCollect(MchAccount mchAccount, String collDate) {

        MchInfo mchInfo = rpcCommonService.rpcMchInfoService.findByMchId(mchAccount.getMchId());
        int riskDay = mchInfo.getRiskDay(); // 风险预存期

        Map map = rpcCommonService.rpcMchAccountHistoryService.selectSettDailyCollect(mchAccount.getMchId(), collDate, MchConstant.FUND_DIRECTION_ADD, riskDay);
        if(map != null) {
            // 交易金额
            Long totalAmount = Long.parseLong(map.get("totalAmount").toString());
            // 平台利润(即商户成本)
            Long totalPlatProfit = Long.parseLong(map.get("totalPlatProfit").toString());
            // 渠道成本
            Long totalChannelCost = Long.parseLong(map.get("totalChannelCost").toString());
            // 交易数
            Integer totalCount = Integer.parseInt(map.get("totalCount").toString());
            MchSettDailyCollect mchSettDailyCollect = new MchSettDailyCollect();
            mchSettDailyCollect.setMchId(mchAccount.getMchId());
            mchSettDailyCollect.setName(mchAccount.getName());
            mchSettDailyCollect.setRiskDay(riskDay);
            mchSettDailyCollect.setCollectDate(DateUtil.str2date(collDate, "yyyy-MM-dd"));
            mchSettDailyCollect.setCollectType(MchConstant.SETT_MODE_HAND); // 手工结算
            mchSettDailyCollect.setSettStatus(MchConstant.PUB_YES);
            mchSettDailyCollect.setTotalAmount(totalAmount);
            mchSettDailyCollect.setTotalPlatProfit(totalPlatProfit);
            mchSettDailyCollect.setTotalChannelCost(totalChannelCost);
            mchSettDailyCollect.setTotalCount(totalCount);
            mchSettDailyCollect.setRemark("");
            rpcCommonService.rpcMchSettDailyCollectService.add(mchSettDailyCollect);
            // 修改账户可结算金额,修改账户资金流水为已结算
            settCollectSuccess(mchAccount.getMchId(), collDate, riskDay, totalAmount, totalPlatProfit);
        }
    }

    // 保证事务
    public void settCollectSuccess(long mchId, String collDate, int riskDay, long totalAmount, long totalPlatProfit) {
        // 更新结算状态
        rpcCommonService.rpcMchAccountHistoryService.updateCompleteSett(mchId, collDate, riskDay);
        // 更新账户可结算金额
        rpcCommonService.rpcMchAccountService.updateSettAmount(mchId, totalAmount-totalPlatProfit);
    }

}
